package com.open.capacity.firebird.util;


import freemarker.template.Configuration;
import freemarker.template.Template;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Map;

public class WordGenerate {

    /**
     * 生成 word 文件
     *
     * @param dataMap  待填充数据
     * @param outPath  输出文件路径
     * @param tmplPath 模板文件路径
     * @param wordTmpl 模板文件名称
     * @param fileName 生成的 word 文件名称
     * @param response 响应流
     */

    public static void WordGenerate(Map dataMap, String outPath, String tmplPath, String wordTmpl, String fileName, HttpServletResponse response) {
        try {
            //Configuration 创建配置实例 用于读取ftl文件
            Configuration configuration = new Configuration(Configuration.VERSION_2_3_30);
            // 设置编码
            configuration.setDefaultEncoding(StandardCharsets.UTF_8.name());

            /**
             * 指定ftl文件所在目录的路径，而不是ftl文件的路径
             */
            // ftl模板文件
//            configuration.setClassForTemplateLoading(WordUtil.class, filePath);
            //我的路径是F：/idea_demo/日报.ftl
            configuration.setDirectoryForTemplateLoading(new File(tmplPath));
            File file = new File(outPath);
            if (!file.exists())
                file.mkdirs();
            //输出文档路径及名称
            File outFile = new File(outPath + fileName);

            //以utf-8的编码读取ftl文件
            Template template = configuration.getTemplate(wordTmpl);
            response.setHeader("Content-disposition",
                    "attachment;filename=" + URLEncoder.encode(fileName + ".doc", StandardCharsets.UTF_8.name()));
            // 定义输出类型
            response.setContentType("application/msword");
            Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile), "utf-8"), 10240);
//            Writer out = new BufferedWriter(new OutputStreamWriter(response.getOutputStream()));
            template.process(dataMap, out);
            out.flush();
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}
